<template>
  <div id="lecture-list">
    <div v-if="role !== 2" class="lecture-top">
      <div :class="{ active: topActive === 0 }" @click="handlestatus(0)">讲座审批</div>
      <div :class="{ active: topActive === 1 }" @click="handlestatus(1)">已完成讲座</div>
    </div>
    <el-form :inline="true" class="demo-form-inline">
      <el-form-item label="宣讲主题">
        <el-input v-model="form.keyword" placeholder="请输入"></el-input>
      </el-form-item>
      <el-form-item v-if="role !== 2" label="宣讲归属">
        <el-cascader
          v-model="form.belong"
          :options="local.teacherOptions"
          :props="props"
          clearable
        ></el-cascader>
      </el-form-item>
      <el-form-item v-if="role !== 2" label="讲师名称">
        <el-input v-model="form.teaName" placeholder="请输入"></el-input>
      </el-form-item>
      <el-form-item v-show="showStatus" label="审核状态">
        <el-select v-model="form.status" clearable placeholder="请选择">
          <el-option
            v-for="val in local.statusOption"
            :key="val.value"
            :value="val.value"
            :label="val.name"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="机构名称" v-if="isPid">
        <casader :pid="form.pid" ref="child"></casader>
      </el-form-item>
      <el-form-item label="演讲日期" v-if="isPid">
        <el-date-picker
          v-model="dateValue"
          value-format="yyyy-MM-dd"
          type="datetimerange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        >
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="blue" icon="el-icon-search" @click="onSubmit">查询</el-button>
        <el-button type="gray" @click="emptyForm">清空</el-button>
      </el-form-item>
      <el-form-item v-if="topActive === 0" class="fr">
        <el-button
          v-if="role !== 2"
          type="green"
          icon="el-icon-check"
          @click="updateStatus(2)"
          >同意</el-button
        >
        <el-button
          v-if="role !== 2"
          type="orange"
          icon="el-icon-close"
          @click="updateStatus(3)"
          >拒绝</el-button
        >
        <el-button v-if="role === 2" type="yellow" @click="toAddLecture"
          >添加讲座</el-button
        >
        <el-button type="cyan" @click="deleteAll">批量删除</el-button>
      </el-form-item>
      <el-form-item v-if="topActive === 1" class="fr">
        <el-button v-if="role !== 2" type="blue" @click="downLoads">数据导出</el-button>
      </el-form-item>
    </el-form>
    <div class="table">
      <el-table
        :data="tableData"
        style="width: 100%"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="50"></el-table-column>
        <el-table-column type="index" label="序号" width="70"></el-table-column>
        <el-table-column prop="title" label="宣讲主题"></el-table-column>
        <el-table-column
          prop="lectureTime"
          label="宣讲时间"
          width="166"
        ></el-table-column>
        <el-table-column
          v-if="role !== 2"
          prop="teacherName"
          label="讲师"
        ></el-table-column>
        <el-table-column prop="address" label="宣讲地址"></el-table-column>
        <el-table-column prop="count" label="人数"></el-table-column>
        <el-table-column prop="orgStr" label="机构"></el-table-column>
        <el-table-column prop="department" label="单位"></el-table-column>
        <el-table-column prop="belongsStr" label="宣讲归属"></el-table-column>
        <el-table-column prop="modelStr" label="宣讲模式"></el-table-column>
        <el-table-column v-if="topActive !== 1" prop="status" label="审核状态">
          <template slot-scope="scope">
            <div v-if="scope.row.status === 0">未提交</div>
            <div v-if="scope.row.status === 1">未审核</div>
            <div class="c-green" v-if="scope.row.status === 2">已通过</div>
            <div class="c-red" v-if="scope.row.status === 3">被拒绝</div>
          </template>
        </el-table-column>
        <el-table-column label="日志" align="center" width="80">
          <template slot-scope="scope">
            <el-button size="mini" type="lightblue" @click="showJournal(scope.row.id)">
              查看
            </el-button>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="200">
          <template slot-scope="scope">
            <!-- 教师 -->
            <div v-if="role === 2">
              <el-button
                v-if="scope.row.status === 2"
                size="mini"
                type="lightblue"
                @click="toDetails(scope.row.id, 'disabled')"
              >
                查看
              </el-button>
              <el-button
                v-if="
                  scope.row.status === 0 ||
                  scope.row.status === 1 ||
                  scope.row.status === 3
                "
                size="mini"
                type="blue"
                @click="toDetails(scope.row.id)"
              >
                编辑
              </el-button>
              <el-button
                v-if="role === 2"
                size="mini"
                type="blue"
                :disabled="scope.row.status == 1 || scope.row.status == 2"
                @click="updateStatus(1, scope.row.id)"
              >
                提交
              </el-button>
            </div>
            <div v-else>
              <el-button
                size="mini"
                type="blue"
                @click="toDetails(scope.row.id, 'disabled')"
              >
                详情
              </el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        v-if="tableData.length > 0"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-size="pageSize"
        layout="total, prev, pager, next, jumper"
        :total="totalCount"
      ></el-pagination>
    </div>
    <!-- 添加/修改 -->
    <el-dialog
      class="add-dialog"
      :close-on-click-modal="false"
      :title="local.dialogInfo.title"
      :visible.sync="dialogAdd"
      width="800px"
      @close="close"
    >
      <el-form :model="form" class="demo-form-inline">
        <el-form-item label="头像">
          <el-upload
            class="avatar-uploader"
            action="/lec/image/upload"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
            accept=".jpg,.jpeg,.JPG,.JPEG"
          >
            <img v-if="imageUrl" :src="imageUrl" class="avatar" />
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
          <div>只能上传jpg文件，尺寸为200px*200px，且不超过10M</div>
        </el-form-item>
        <el-form-item label="姓名">
          <el-input v-model="formAdd.name" placeholder="请输入"></el-input>
        </el-form-item>
        <el-form-item label="性别">
          <el-select v-model="formAdd.sex" placeholder="请选择">
            <el-option
              v-for="val in local.sexOption"
              :key="val.id"
              :value="val.id"
              :label="val.name"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="年龄">
          <el-input v-model="formAdd.age" placeholder="请输入"></el-input>
        </el-form-item>
        <el-form-item label="电话">
          <el-input v-model="formAdd.phone" placeholder="请输入"></el-input>
        </el-form-item>
        <el-form-item label="账号">
          <el-input v-model="formAdd.account" placeholder="请输入"></el-input>
        </el-form-item>
        <el-form-item label="省份">
          <el-select v-model="formAdd.province" placeholder="请选择">
            <el-option
              v-for="(val, index) in local.provinceOption"
              :key="index"
              :value="val"
              :label="val"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="单位">
          <casader :pid="formAdd.department" ref="dialogChild"></casader>
        </el-form-item>
        <el-form-item label="职务">
          <el-input v-model="formAdd.profession" placeholder="请输入"></el-input>
        </el-form-item>
        <el-form-item label="宣讲方向">
          <el-input v-model="formAdd.direction" placeholder="请输入"></el-input>
        </el-form-item>
        <el-form-item label="简介">
          <el-input
            type="textarea"
            :rows="2"
            v-model="formAdd.description"
            placeholder="请输入"
          >
          </el-input>
        </el-form-item>
      </el-form>
      <div style="width: 70px; margin: 0 auto">
        <el-button v-if="local.dialogInfo.isAdd" type="primary" @click="saveAdd(1)"
          >保存</el-button
        >
        <el-button v-else type="primary" @click="saveAdd(2)">保存修改</el-button>
      </div>
    </el-dialog>
    <!-- 日志 -->
    <el-dialog
      class="add-dialog"
      :close-on-click-modal="false"
      title="审核日志"
      :visible.sync="dialogJournal"
      width="800px"
      @close="close"
    >
      <div class="table">
        <el-table
          :data="tableDataJournal"
          style="width: 100%"
          @selection-change="handleSelectionChange"
        >
          <el-table-column type="index" label="序号" width="70"></el-table-column>
          <el-table-column prop="adminName" label="审批人"></el-table-column>
          <el-table-column prop="statusStr" label="审批状态"></el-table-column>
          <el-table-column prop="remark" label="审批意见"></el-table-column>
          <el-table-column prop="createTime" label="审批时间"></el-table-column>
        </el-table>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getToken } from "@/utils/auth";
import Casader from "../components/cascaderD";
export default {
  components: { Casader },
  data() {
    return {
      props: { multiple: true },
      tableDataJournal: [],
      dialogJournal: false,
      dateValue: [],
      role: "",
      showStatus: true,
      topActive: 0,
      pid: "",
      //弹框是否为修改
      isEdit: false,
      imageUrl: "",
      //是否读取完pid
      isPid: false,
      //删除数组
      ids: [],
      //添加
      dialogAdd: false,
      form: {
        keyword: "",
        status: "",
        pid: 0,
        teaName: "",
        belong: [],
      },
      //添加列表
      formAdd: {
        name: "",
        head: "",
        sex: "",
        age: "",
        phone: "",
        account: "",
        province: "",
        profession: "",
        department: 0,
        direction: "",
        description: "",
      },
      local: {
        teacherOptions: [],
        //弹框信息
        dialogInfo: {
          name: "添加讲师",
          isAdd: true,
        },
        statusOption: [
          {
            name: "未提交",
            value: 0,
          },
          {
            name: "未审核",
            value: 1,
          },
          {
            name: "已通过",
            value: 2,
          },
          {
            name: "被拒绝",
            value: 3,
          },
        ],
        teacherDetails: {
          id: "",
          name: "",
          head: {
            fullUrl: "",
            shortUrl: "",
          },
          sex: "",
          age: "",
          phone: "",
          account: "",
          path: [1],
          province: "",
          profession: "",
          direction: "",
          description: "",
        },
      },
      //权限列表
      roleOption: [],
      //修改
      dialogEdit: false,
      currentPage: 1,
      pageSize: 10,
      totalCount: 1000,
      tableData: [],
      aid: 0,
    };
  },
  created() {},
  mounted() {
    this.$nextTick(() => {
      this.init();
    });
  },
  methods: {
    init() {
      console.log(getToken() - 0, 555);
      this.role = getToken() - 0;
      console.log(this.role, 666);
      if (this.role !== 2) {
        this.getPid();
        this.getTeacherTypes();
      } else {
        this.getList();
      }
      console.log(this.role, 223);
    },
    showJournal(id) {
      console.log(id, 22);
      this.$http.get(`/course/log?id=${id}`).then((response) => {
        let res = response.data;
        if (res.code == "200") {
          console.log(res, 1666666);
          this.dialogJournal = true;
          this.tableDataJournal = res.data;
        } else {
          this.$message.error(res.message);
        }
      });
    },
    //获取讲师类型，宣讲归属
    getTeacherTypes() {
      this.$http.get(`/teacher/types`).then((response) => {
        let res = response.data;
        if (res.code == "200") {
          console.log(res, 1666666);
          this.local.teacherOptions = res.data;
        } else {
          this.$message.error(res.message);
        }
      });
    },
    //获取pid
    getPid() {
      let self = this;
      self.$http.get("/admin/pid").then((response) => {
        let res = response.data;
        if (res.code == "200") {
          console.log(res, 111222);
          self.isPid = true;
          self.pid = res.data;
          self.form.pid = res.data;
          self.formAdd.org = self.pid;
          console.log(self.form.pid, 2222222);
          self.$nextTick(function () {
            if (this.$route.query.type) {
              self.handlestatus(1);
            } else {
              self.getList();
            }
          });
        } else {
          self.$message.error(res.message);
        }
      });
    },
    //下载
    downLoads() {
      let self = this;
      const loading = self.$loading({
        lock: true,
        text: "加载中...",
        spinner: "el-icon-loading",
        background: "rgba(0, 0, 0, 0.7)",
      });
      let pid = self.$refs.child.cx();
      let startTime = "";
      let endTime = "";
      if (self.dateValue && self.dateValue.length) {
        startTime = self.dateValue[0];
        endTime = self.dateValue[1];
      }
      let obj = {
        keyword: self.form.keyword, //关键字
        status: self.form.status, //状态
        org: pid, //机构
        teaName: self.form.teaName, //教师名称
        belong: self.form.belong, //宣讲属于
        startTime: startTime, //开始时间
        endTime: endTime, //结束时间
      };
      self.$http
        .post(`/course/download`, obj, { responseType: "blob" })
        .then((response) => {
          let blob = new Blob([response.data], {
            type: response.headers["content-disposition"],
          });
          //console.log(response.headers['content-disposition'],55555);
          let fileName = "讲座列表.zip";
          let url = window.URL.createObjectURL(blob);
          let downloadElement = document.createElement("a");
          downloadElement.style.display = "none";
          downloadElement.href = url;
          downloadElement.download = fileName; //下载后文件名
          document.body.appendChild(downloadElement);
          downloadElement.click(); //点击下载
          document.body.removeChild(downloadElement); //下载完成移除元素
          window.URL.revokeObjectURL(url);
          loading.close();
          console.log(1234);
        })
        .catch((err) => {
          console.log(err);
          loading.close();
        });
    },
    toAddLecture() {
      this.$router.push({
        path: "AddLecture",
      });
    },
    handlestatus(type) {
      if (type === 0) {
        this.topActive = 0;
        this.form.status = "";
        this.showStatus = true;
      }
      if (type === 1) {
        this.topActive = 1;
        this.form.status = 2;
        this.showStatus = false;
      }
      this.getList();
    },
    //清空
    emptyForm() {
      this.form.keyword = "";
      if (this.showStatus) {
        this.form.status = "";
      }
    },
    handleAvatarSuccess(res, file) {
      this.imageUrl = URL.createObjectURL(file.raw);
      this.formAdd.head = res.data;
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === "image/jpeg";
      const isLt2M = file.size / 1024 / 1024 < 10;

      if (!isJPG) {
        this.$message.error("上传头像图片只能是 JPG 格式!");
        return false;
      }
      if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 10MB!");
      }
      return isJPG && isLt2M;
    },
    //添加修改保存
    saveAdd(type) {
      let self = this;
      self.formAdd.head = self.imgUrl;
      let pid = self.$refs.dialogChild.cx();
      self.formAdd.department = pid;
      let url = "";
      //修改
      if (type === 1) {
        url = "/teacher/add";
      }
      //修改
      if (type === 2) {
        url = "/teacher/update";
      }
      self.$http
        .post(url, self.formAdd)
        .then((response) => {
          let res = response.data;
          if (res.code == "200") {
            self.$message.success("保存成功");
            self.dialogAdd = false;
            self.getList();
          } else {
            self.$message.error(res.message);
          }
        })
        .catch((err) => {
          self.$message.error(err.message);
        });
    },
    //关闭
    close() {
      this.imageUrl = "";
      this.formAdd = {
        name: "",
        head: "",
        sex: "",
        age: "",
        phone: "",
        account: "",
        province: "",
        profession: "",
        department: "",
        direction: "",
        description: "",
      };
    },
    //添加讲师弹窗
    addTeacher() {
      this.local.dialogInfo.title = "添加讲师";
      this.local.dialogInfo.isAdd = true;
      this.dialogAdd = true;
    },
    //查看详情
    toDetails(id, disabled) {
      if (disabled) {
        this.$router.push({
          path: "addLecture",
          query: {
            id: id,
            disabled: disabled,
          },
        });
      } else {
        this.$router.push({
          path: "addLecture",
          query: {
            id: id,
          },
        });
      }
    },
    //修改讲座状态
    updateStatus(type, id) {
      let self = this;
      let ids = [];
      if (id) {
        ids.push(id);
      } else {
        ids = self.ids;
      }
      if (!ids.length) {
        self.$message.error("请勾选数据");
        return;
      }
      self.$http.post(`/course/review?status=${type}`, ids).then((response) => {
        let res = response.data;
        if (res.code == "200") {
          self.$message.success(res.message);
          self.getList();
        } else {
          self.$message.error(res.message);
        }
      });
    },
    //获取列表
    getList() {
      let self = this;
      let obj = {};
      //管理员
      if (self.role !== 2) {
        console.log(self.$refs.child, 234);
        let pid = self.$refs.child.cx();

        let startTime = "";
        let endTime = "";
        console.log(self.dateValue, 222222);
        if (self.dateValue && self.dateValue.length) {
          startTime = self.dateValue[0];
          endTime = self.dateValue[1];
        }
        obj = {
          pageNum: self.currentPage,
          pageSize: self.pageSize,
          keyword: self.form.keyword,
          status: self.form.status,
          startTime: startTime,
          endTime: endTime,
          belong: self.form.belong,
          org: pid,
          teaName: self.form.teaName,
        };
      }
      //教师
      else {
        obj = {
          pageNum: self.currentPage,
          pageSize: self.pageSize,
          keyword: self.form.keyword,
          status: self.form.status,
        };
      }
      self.$http
        .post(
          //   `/course/list?pageNum=${self.currentPage}&pageSize=${self.pageSize}&keyword=${self.form.keyword}&status=${self.form.status}`,
          "/course/list",
          obj
        )
        .then((response) => {
          let res = response.data;
          if (res.code == "200") {
            console.log(res, 1);
            self.tableData = res.data.content;
            self.totalCount = res.data.total;
            console.log(self.tableData, 111);
          } else {
            self.$message.error(res.message);
          }
        });
    },
    handleSelectionChange(rows) {
      console.log(rows, 1111);
      this.ids = rows.map((item) => item.id);
    },
    //查询
    onSubmit() {
      this.currentPage = 1;
      this.getList();
    },
    //分页
    handleSizeChange: function (size) {
      this.pageSize = size;
    },
    handleCurrentChange: function (currentPage) {
      this.currentPage = currentPage;
      this.getList();
    },

    //批量删除
    deleteAll() {
      let self = this;
      let ids = self.ids;
      console.log(ids, 1122);
      if (!ids.length) {
        self.$message.error("请选择要删除的数据");
        return;
      }
      self
        .$confirm("是否删除选中?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        })
        .then(() => {
          self.$http.post("/course/delete", ids).then(
            (response) => {
              let res = response.data;
              if (res.code == "200") {
                self.$message.success("删除成功");
                self.ids = [];
                self.currentPage = 1;
                self.getList();
              } else {
                self.$message.error(res.message);
              }
            },
            (err) => {
              console.log("err");
            }
          );
        })
        .catch(() => {});
    },
  },
};
</script>

<style lang="scss">
#lecture-list {
  .lecture-top {
    display: flex;
    align-items: center;
    border-bottom: 1px solid #e6e6e6;
    margin-bottom: 20px;
    > div {
      height: 54px;
      line-height: 54px;
      padding: 0 10px;
      font-size: 14px;
      font-family: Microsoft YaHei;
      font-weight: 400;
      color: #999999;
      margin-right: 20px;
      cursor: pointer;
    }
    .active {
      color: #2d2d2d;
      border-bottom: 2px solid #6ebbe5;
    }
  }
  .el-input {
    width: auto;
  }
  .add-dialog {
    .el-cascader {
      width: auto !important;
    }
  }
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409eff;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
  .c-green {
    color: #38b03f;
  }
  .c-red {
    color: #ea644a;
  }
}
</style>
